package com.gcloud.mesh.alert.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gcloud.mesh.alert.dao.RuleDao;
import com.gcloud.mesh.alert.entity.RuleEntity;
import com.gcloud.mesh.header.msg.alert.CreateRuleMsg;
import com.gcloud.mesh.header.msg.alert.DeleteRuleMsg;
import com.gcloud.mesh.header.vo.alert.RuleVo;

@Service
public class RuleService {

	@Autowired
	private RuleDao ruleDao;

	public void create(CreateRuleMsg msg) {
		for (RuleVo vo : msg.getRuleVos()) {
			RuleEntity entity = new RuleEntity();
			entity.setPolicyId(msg.getPolicyId());
			entity.setCreateTime(new Date());
			entity.setDuration(vo.getDuration());
			entity.setEnabled(vo.getEnabled());
			entity.setId(UUID.randomUUID().toString());
			entity.setLevel(vo.getLevel());

			entity.setMeter(vo.getMeter());
			entity.setResourceType(vo.getResourceType());
			entity.setResourceId(vo.getResourceId());

			entity.setThreshold(vo.getThreshold());
			entity.setStatistics(vo.getStatistics());
			entity.setComparisonOperator(vo.getComparisonOperator());
			ruleDao.save(entity);
		}

	}

	public void delete(DeleteRuleMsg msg) {
		ruleDao.deleteById(msg.getRuleId());
	}

	public List<RuleVo> getAlarmRules(String key, String value) {
		List<RuleVo> ruleVos = new ArrayList<RuleVo>();
		for (RuleEntity entity : ruleDao.findByProperty(key, value)) {
			RuleVo vo = new RuleVo();
			vo.setComparisonOperator(entity.getComparisonOperator());
			vo.setCreateTime(entity.getCreateTime());
			vo.setDuration(entity.getDuration());
			vo.setEnabled(entity.isEnabled());
			vo.setId(entity.getId());
			vo.setLevel(entity.getLevel());
			vo.setMeter(entity.getMeter());
			vo.setPolicyId(entity.getPolicyId());
			vo.setResourceType(entity.getResourceType());
			vo.setResourceId(entity.getResourceId());
			vo.setStatistics(entity.getStatistics());
			vo.setThreshold(entity.getThreshold());
			ruleVos.add(vo);
		}
		return ruleVos;
	}
}
